package com.yin.ketech.util;

import cn.hutool.core.lang.UUID;
import com.yin.ketech.common.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author luzw
 * @version V1.0
 * @className RedisTokenUtils
 * @description TODO
 * @date 2020/6/4
 **/
@Component
public class RedisTokenUtils {

    @Autowired
    private RedisService redisService;

    /***
     * 携带token的头
     */
    public static final String TOKEN_HEADER = "Authorization";
    /***
     * token解析的前缀
     */
    public static final String TOKEN_PARSE_PREFIX = "Bearer ";
    /***
     * token存放在redis中的前缀
     */
    public static final String TOKEN_STORE_PREFIX = "energy:token:";

    /***
     * 默认key的过期时间为1小时
     */
    private static final int EXPIRATION = 3600;

    /***
     * 默认key的过期时间小于20分钟时，重置token的过期时间
     */
    private static final int EXPIRATION_THRESHOLD = 1200;

    /***
     * 时间单位默认为秒
     */
    private static final TimeUnit DEFAULT_TIMEUNIT = TimeUnit.SECONDS;

    /***
     * 创建token
     * @param username
     * @return
     */
    public String createToken(String username){
        String token = UUID.fastUUID().toString();
        redisService.setCacheObject(TOKEN_STORE_PREFIX + token, username, EXPIRATION, DEFAULT_TIMEUNIT);
        return token;
    }

    /***
     * 刷新token的过期时间
     * @param token
     */
    public void refreshToken(String token){
        redisService.expire(TOKEN_STORE_PREFIX + token, EXPIRATION, DEFAULT_TIMEUNIT);
    }

    /***
     * 是否过期
     * @param token
     * @return
     */
    public boolean isExpiration(String token){
        Long expireTime = redisService.getExpire(TOKEN_STORE_PREFIX + token, DEFAULT_TIMEUNIT);
        return expireTime > 0;
    }

    /***
     * 获取用户名
     * @param token
     * @return
     */
    public String getUsername(String token){
        return redisService.getCacheObject(TOKEN_STORE_PREFIX + token);
    }

    /***
     * 如果过期了返回false, 如果快过期，重置过期时间返回true
     * @param token
     * @return
     */
    public void refreshTokenIfExpiringSoon(String token){
        Long expireTime = redisService.getExpire(TOKEN_STORE_PREFIX + token, DEFAULT_TIMEUNIT);
        if(expireTime <= EXPIRATION_THRESHOLD){
            refreshToken(token);
        }
    }

    /***
     *  移除token
     * @param token
     * @return
     */
    public void removeToken(String token){
        redisService.deleteObject(TOKEN_STORE_PREFIX + token);
    }

}
